package com.fragrance.controller;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fragrance.cfg.FragranceJFinalCfg;
import com.jfinal.core.Controller;
import com.jfinal.render.ContentType;

public class WeChatMsgController  extends Controller{
	
	private Logger logger = LoggerFactory.getLogger(WeChatMsgController.class);

	private final static String METHOD_GET = "GET";
	
	private final static String METHOD_POST = "POST";
	
	/**
	 * 微信验证
	 */
	public void doMsg(){
		String method = getRequest().getMethod();
		HttpServletRequest request = getRequest();
		HttpServletResponse response =  getResponse();
		logger.info("method = " + method);
		if(METHOD_GET.equals(method)){
			String signature = request.getParameter("signature");
			String timestamp = request.getParameter("timestamp");
			String nonce = request.getParameter("nonce");
			String echostr = request.getParameter("echostr");
			String[] arrs = {FragranceJFinalCfg.weChatProp.get("wechat.token"),nonce,timestamp};
			Arrays.sort(arrs);
			StringBuffer sb = new StringBuffer();
			for(String a:arrs) {
				sb.append(a);
			}
			String sha1 = sha1(sb.toString());
			if(signature.equals(sha1)) {
				renderText(echostr);
			}else{
				logger.info("验证失败signature="+signature +",sha1="+sha1);
			}
		}else if(METHOD_POST.equals(method)){
			try {
				request.setCharacterEncoding("utf-8");
				response.setContentType("text/xml;charset=utf-8");
				response.setCharacterEncoding("utf-8");
				String returnMsg = null;
				logger.info("returnMsg = " + returnMsg);
				if(StringUtils.isNotBlank(returnMsg)) {
					renderText(returnMsg, ContentType.XML);
				}else{
					logger.info("会送数据失败");
				}
			} catch (Exception e) {
				logger.info("会送数据发生异常", e);
			}
		}else{
			logger.info("请求方式有误");
		}
	}

	
	private  String sha1(String str) {
		try {
			StringBuffer sb = new StringBuffer();
			MessageDigest md = MessageDigest.getInstance("sha1");
			md.update(str.getBytes());
			byte[] msg = md.digest();
			for(byte b:msg) {
				sb.append(String.format("%02x",b));
			}
			return sb.toString();
		} catch (NoSuchAlgorithmException e) {
			logger.error("sha1发生异常", e);
		}
		return null;
	}

}
